# -*- coding: utf-8 -*-
# ///////////////////////////////////////////////////////////////
# @File    :   main.py
# @Time    :   2024/07/04 15:59:11
# @Author  :   kai.luo
# @Version :   1.0.0
# @Desc    :   python3.9.2
# PaddlePaddle库要求
# 1. 操作系统要求：
#   Windows 7 / 8 / 10，专业版 / 企业版
#   Ubuntu 16.04 / 18.04 / 20.04
#   CentOS 7
#   MacOS 10.11 / 10.12 / 10.13 / 10.14
#   操作系统要求是 64 位版本
# 2. 处理器要求
#   处理器支持 MKL
#   处理器架构是x86_64（或称作 x64、Intel 64、AMD64）架构，目前PaddlePaddle不支持arm64架构（mac M1除外，paddle 已支持Mac M1 芯片）
# 3. Python 和 pip 版本要求
#   Python 的版本要求 3.6/3.7/3.8/3.9/3.10(python版本请注意python3.11可能有问题)
#   Python 具有 pip, 且 pip 的版本要求 20.2.2+
#   Python 和 pip 要求是 64 位版本
# 4. PaddlePaddle 对 GPU 支持情况
#   目前 PaddlePaddle 支持 NVIDIA 显卡的 CUDA 驱动和 AMD 显卡的 ROCm 架构
#   需要安装 cuDNN ，版本要求 7.6(For CUDA10.1/10.2)
#   如果您需要 GPU 多卡模式，需要安装 NCCL 2
# 5. 命令
#   python3.10
#   python -m pip install --upgrade pip
#   python -m pip install paddlepaddle==3.0.0b0 -i https://www.paddlepaddle.org.cn/packages/stable/cpu/
#   pip install paddleocr
#   pip3 install -U https://paddleocr.bj.bcebos.com/whl/layoutparser-0.0.0-py3-none-any.whl
#
# draw_structure_result, save_structure_res
# ///////////////////////////////////////////////////////////////

# type: ignore
# from paddleocr import PaddleOCR, PPStructure
import sys
import traceback
from PySide6.QtWidgets import *
from PySide6.QtGui import *
from PySide6.QtCore import *
from ui.PaddleMainUI_ui import Ui_MainWindow
from moudles.Common.dragImage import DragImage
from moudles.Common.jpgToPng import Jpg2Png
from moudles.MedicalReportForm.medicalReportForm import MedicalReportForm
from moudles.ColorDopplerReportForm.colorDopplerReportForm import ColorDopplerReportForm
from moudles.Common.common import *
from moudles.Common.displayCheckReportUI import DisplayCheckReport
from moudles.Common.displayColorCheckReportUI import DisplayColorCheckReport


class SignalWork(QThread):
    """
    多线程执行程序
    Args:
        QObject (_type_): _description_
    """
    data_received = Signal(list)  # 用于传递收到的数据信号

    def __init__(self, image_names, mianUI):
        super().__init__()

        self.mianUI = mianUI
        self.image_names = image_names
        # 初始化医疗报告单对象
        self.medicalReportForm = MedicalReportForm()
        self.colorDopplerReportForm = ColorDopplerReportForm()

    def run(self):
        error = '识别错误：可能原因：您上传了非正规化验单图片、上传的图片不完整或模糊'
        # 开始获取每张图片的数据信息
        for index, scr_image_path in enumerate(self.image_names):
            # self.mianUI.statusbar.setText(f'正在解析图片{scr_image_path}.....')
            try:
                if self.mianUI.parserImageType == '检验报告单':
                    image_formData_dict = self.medicalReportForm.parserPPStructure(scr_image_path)
                else:
                    image_formData_dict = self.colorDopplerReportForm.parserPPStructure(scr_image_path)

                if image_formData_dict:
                    self.data_received.emit([scr_image_path, image_formData_dict])
                else:
                    self.data_received.emit([scr_image_path, [{'检测医院名称': error}]])
            except:
                self.data_received.emit([scr_image_path, [{'检测医院名称': error}]])
            finally:
                # self.mianUI.statusbar.setText(f'解析图片{scr_image_path}完成。')
                pass

    def run_test(self):
        for index, scr_image_path in enumerate(self.image_names):
            image_formData_dict = self.medicalReportForm.parserPPStructure(scr_image_path)
            self.data_received.emit([scr_image_path, image_formData_dict])


class MainWindow(QMainWindow, Ui_MainWindow):
    def __init__(self) -> None:
        super().__init__()

        # 添加主页面
        self.setupUi(self)
        self.setWindowIcon(QIcon('ui/icons/logo.ico'))
        self.appTitle = '智能识别系统'
        self.setWindowTitle(self.appTitle)

        # 初始化参数
        self.checkedItems = list()
        self.all_image_formData_dict = dict()  # 所有图片的数据字典
        self.image_num = 0  # 文件总数
        self.parsered_counter = 0  # 已解析图片计数器
        self.parserImageType = ''  # 解析图片的类型

        # 彩超
        self.all_color_image_formData_dict = dict()  # 所有图片的数据字典

        # 在toolbox第一页添加临时值
        page1_layout = QVBoxLayout()
        page1_label = QLabel('暂无样本')
        page1_label.setObjectName('todoText')
        page1_layout.addWidget(page1_label)
        self.toolBox.widget(0).setLayout(page1_layout)

        self.h_layout = QVBoxLayout()

        # 初始化jpg转png
        self.jpgToPng = Jpg2Png()

    def showImage(self, img_path):
        """
        在组建中展示图片
        Args:
            img_path (_type_): 图片路径
        """
        self.scene = QGraphicsScene()
        self.graphicsView.setScene(self.scene)

        self.image_item = QGraphicsPixmapItem(QPixmap(img_path))
        self.scene.addItem(self.image_item)

        self.graphicsView.setSceneRect(self.image_item.boundingRect())

        dragImage = DragImage(self)
        dragImage.setDragMode()
        dragImage.setZoomMode()

    def loadImage(self):
        """
        导入图片
        """
        self.image_names, _ = QFileDialog.getOpenFileNames(self, "选择图片", "", "JPG/PNG Files (*.jpg *.png);")
        if self.image_names:
            # print(f'image_names---{self.image_names}')
            self.all_image_formData_dict = dict()
            self.displayImageNames(False, self.image_names)
            self.image_num = len(self.image_names)

    def displayImageNames(self, isCheckedFlag, image_names):
        """
        展示图片的路径
        Args:
            image_names (_type_): 图片绝对路径列表
        """
        for i in reversed(range(self.h_layout.count())):
            widget = self.h_layout.itemAt(i).widget()
            if widget is not None:
                widget.deleteLater()

        self.h_layout.setSpacing(1)
        for image_path in image_names:
            # 创建 QCheckBox
            checkbox = QCheckBox(image_path)
            checkbox.setChecked(isCheckedFlag)
            self.h_layout.addWidget(checkbox)
            # 添加一个标签显示选择的条目
            label = QLabel()
            self.h_layout.addWidget(label)
            # 连接信号槽以获取勾选的条目
            checkbox.stateChanged.connect(self.getImagePathLabel)

        self.toolBox.widget(1).setLayout(self.h_layout)

        # print(f'self.h_layout.count()------{self.h_layout.count()}')

    def startParserImage(self):
        """
        开始检验单
        """
        # self.pushButton_5.setEnabled(False)
        self.parserImageType = '检验报告单'
        self.parsered_counter = 0

        # 启动多线程
        self.signal_worker = SignalWork(self.image_names, self)
        self.signal_worker.data_received.connect(self.on_iamgeData_received)
        # self.signal_worker.start()
        self.signal_worker.run_test()

    @Slot(list)
    def on_iamgeData_received(self, data):
        """
        图片路径对应的数据
        Args:
            data (_type_): _description_
        """
        # print(f'on_iamgeData_received----{data}')
        img_path, img_data = data
        self.all_image_formData_dict.setdefault(img_path, img_data)

        self.parsered_counter += 1
        self.pushButton_4.setText('开始(检验单) '+f' {self.parsered_counter}'+' / '+f'{self.image_num}')

    def startParserColorImage(self):
        """
        开始彩超
        """
        # self.pushButton_4.setEnabled(False)
        self.parserImageType = '彩超报告单'
        self.parsered_counter = 0

        # 启动多线程
        self.signal_worker = SignalWork(self.image_names, self)
        self.signal_worker.data_received.connect(self.received_colorReport_data)
        self.signal_worker.start()

    @Slot(list)
    def received_colorReport_data(self, data):
        """
        图片路径对应的数据
        Args:
            data (_type_): _description_
        """
        # print(f'on_iamgeData_received----{data}')
        img_path, img_data = data
        self.all_color_image_formData_dict.setdefault(img_path, img_data)
        # print(f'img_path----{img_path}')

        self.parsered_counter += 1
        self.pushButton_5.setText('开始(彩超) '+f' {self.parsered_counter}'+' / '+f'{self.image_num}')

    def getImagePathLabel(self):
        """
        获取点击的label对应的图片路径
        Args:
            image_path (_type_): 图片路径
        """
        # 清楚数据
        self.clearFormData()
        # 图片路径
        sender_text = self.sender().text()

        # 显示图片
        self.showImage(sender_text)

        # 界面展示
        if self.parserImageType == '检验报告单':
            # replaceWidget(self.gridLayout_10, self.widget, ultrasonicUi)  # 替换组件
            displayCheckReport = DisplayCheckReport(self)
            displayCheckReport.displayCheckReport(sender_text, self.all_image_formData_dict)
        elif self.parserImageType == '彩超报告单':
            displayColorCheckReport = DisplayColorCheckReport(self)
            displayColorCheckReport.displayColorCheckReport(sender_text, self.all_color_image_formData_dict)

    def selectAllImage(self):
        """
        全选
        """
        if self.allCheckBox.isChecked():
            self.displayImageNames(True)
        else:
            self.displayImageNames(False)

    def clearFormData(self):
        #
        self.nameEdit.clear()
        self.sexEdit.clear()
        self.ageEdit.clear()
        self.numberEdit.clear()
        self.departmentEdit.clear()
        self.situationEdit.clear()
        self.telEdit.clear()
        self.samplingEdit.clear()
        self.recevieEdit.clear()

        #
        self.tableWidget.clearContents()
        #
        self.inspectorEdit.clear()
        self.reviewerEdit.clear()
        self.hospitalTelEdit.clear()
        self.reportDataEdit.clear()
        self.hospitalAddrEdit.clear()

    def copyResultText(self):
        self.image_color_counter += 1
        pushButton_text = self.pushButton_5.text()
        self.pushButton_5.setText(pushButton_text+f' {self.image_color_counter}'+' / '+f'{self.image_num}')

    # def closeEvent(self, event):
    #     # Ensure the thread is properly terminated when closing the window
    #     if self.thread and self.thread.isRunning():
    #         self.thread.requestInterruption()
    #         self.thread.wait()
    #     super().closeEvent(event)


if __name__ == '__main__':
    app = QApplication(sys.argv)
    app.setStyle(QStyleFactory.create('Fusion'))
    loadStyle(app)
    # ultrasonicUi = UltrasonicUi()
    windowns = MainWindow()
    windowns.show()
    sys.exit(app.exec())
